package org.ilead.iserve.service.impl;

import java.util.List;

import org.ilead.iserve.dao.IUserDAO;
import org.ilead.iserve.model.User;
import org.ilead.iserve.service.IUserService;

public class UserService implements IUserService {
	
	private IUserDAO userDAO;

	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Override
	public boolean hasNameRegister(String loginName) {
		List<User> userList = userDAO.findByLoginName(loginName);
		return userList != null && userList.size() > 0;
	}
	
	@Override
	public boolean hasEmailRegister(String email) {
		List<User> userList = userDAO.findByProperty(IUserDAO.EMAIL, email);
		return userList != null && userList.size() > 0;
	}

	public void addUser(User u) throws Exception {
		userDAO.save(u);
	}

	public void delUserById(Integer id) throws Exception {
		userDAO.deleteById(id);
	}

	public List<User> findAll() {
		return userDAO.findAll();
	}
	
	public List<User> findByPermission(int permission){
		return userDAO.findByPermission(permission);
	}

	public List<User> findByLoginName(String uname) {
		return userDAO.findByLoginName(uname);
	}

	public User findById(Integer id) {
		return userDAO.findById(id);
	}

	public User login(String uname, String upass) {

		List list = userDAO.findByLoginName(uname);
		if (null == list || list.size() == 0)
			return null;
		User u = (User) list.get(0);
		if (null == u)
			return null;
		if (uname.equals(u.getLoginName()) && upass.equals(u.getPassword()))
			return u;
		else
			return null;
	}

	public void updateUser(User u) throws Exception {
		userDAO.attachDirty(u);
	}

}
